#Get objects
old_ws = ls()


################################################
#Islamist Voteshare by Province and NVMS Status#
################################################

#Islamist voteshare by province
province_names = mergedTable_podes[, list(count = .N), by = list(id_prov, provinsi)] %>% 
  .[!is.na(id_prov), list(Province = provinsi[which.max(count)]) , by = id_prov]

province_elections = dapil_elections_all[, list(islamist_votes = sum(all_IT_vs, na.rm = T),
                                                total_votes = sum(all_total_votes, na.rm = T), count = .N), by = list(id_prov, province, election_cycle, nvms)]
province_elections[, id_prov := as.numeric(id_prov)]
#Islamist voteshare by NVMS/Non-NVMS province
nvms_elections = dapil_elections_all[, list(islamist_votes = sum(all_IT_vs, na.rm = T),
                                            total_votes = sum(all_total_votes, na.rm = T), count = .N), by = list(nvms)]
nvms_elections[, islamist_vs := islamist_votes/total_votes ]

setkey(province_elections, id_prov)
setkey(province_names, id_prov)

plot_data = province_names[province_elections] %>% .[,  list(islamist_votes = sum(islamist_votes, na.rm = T),
                                                             total_votes = sum(total_votes, na.rm = T)
), by = list(id_prov, Province, election_cycle, nvms)]
plot_data[, it_voteshare := islamist_votes/total_votes]
setkey(plot_data, election_cycle, it_voteshare)

pdf('./output/figures/figure_e1.pdf', width=7.5, height = 6)
p = ggplot(plot_data, aes(x = reorder(Province, it_voteshare), y = it_voteshare, fill = nvms)) +
  geom_bar(stat = 'identity') + facet_grid(election_cycle ~ .) + 
  ylab("Islamist Voteshare") + xlab("Province") + labs(fill='NVMS Sample') +
  theme_bw() + theme(axis.text.x = element_text(angle = 90, hjust = 1)) + 
  theme(legend.position="bottom")
print(p)
dev.off()


#cleanup
drop = setdiff(ls(), c(old_ws)) 
rm(list = drop)